package com.joint.web.action.party;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.RoleService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.*;
import com.joint.core.entity.SelectionIssued;
import com.joint.core.service.*;
import com.joint.core.service.SelectionIssuedService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dqf on 2015/8/26.
 */
@ParentPackage("party")
public class AjaxSelectionissuedAction extends BaseFlowAction {
  
    @Resource
    private SelectionIssuedService selectionIssuedService;
    @Resource
    private SelectionPublicityService selectionPublicityService;
    @Resource
    private  SelectionNoticeService selectionNoticeService;

    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private RoleService roleService;

    private SelectionIssued selectionIssued;

    private int numStatus;
    private Users loginUser;

    private boolean flag;



    //附件对象id
    private String issuedAttchmentId;

    /**
     * 公告对象
     */
    private SelectionNotice selectionNotice;
       /**
     * 聘书发放
     */
    private List<FileManage> attchment;
    /**
     * 聘书发放文本
     */
    private String attchmentText;
    /**
     * 聘任开始时间
     */
    private Date issueStartDate;
    /**
     * 聘任结束时间
     */
    private Date issueEndDate;

    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        selectionNotice=new SelectionNotice();
        flag=false;
        if(StringUtils.isNotEmpty(parentId)){
            pager=new Pager();
            Company company=usersService.getCompanyByUser();
            Users users=usersService.getLoginInfo();
            Map<String, Object> params=new HashMap<String, Object>();
            params=getSearchFilterParams(_search,params,filters);
            params.put("company",company);
            params.put("state",BaseEnum.StateEnum.Enable);
            selectionNotice=selectionNoticeService.get(parentId);
            params.put("selectionNotice",selectionNotice);
            params.put("result","1");
            params.put("processState",FlowEnum.ProcessState.Finished);
            pager=selectionPublicityService.findByPager(pager,params);
            List<SelectionPublicity> selectionPublicityList;
            if(pager.getTotalCount()>0){
                selectionPublicityList=(List<SelectionPublicity>)pager.getList();
            }else {
                selectionPublicityList=new ArrayList<>();
            }
            if(selectionPublicityList.size()>0){
                flag=true;
            }
        }else{

        }


        return "selectionissued";
    }


    public String listfordialog(){

        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);


        pager=selectionIssuedService.findByPagerAndProcessState(pager, user, "selectionissued", FlowEnum.ProcessState.Finished, params);
        List<SelectionIssued> proInfoList;
        if (pager.getTotalCount() > 0){
            proInfoList = (List<SelectionIssued>) pager.getList();
        }else{
            proInfoList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(SelectionIssued mproInfo:proInfoList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",mproInfo.getId());
            rMap.put("name",mproInfo.getName());
            //rMap.put("no",mproInfo.getProjectNo());
            rMap.put("create",mproInfo.getCreater().getName());

            String sAddr = "";

            // rMap.put("buildAddress" , mproInfo.getBuildAddress());

            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //公告对象
        selectionNotice=new SelectionNotice();
        if(StringUtils.isNotEmpty(parentId)){
            String[] str=parentId.split(",");
            for(int i=0;i<str.length-1;i++){
                if(str[i].trim()==str[i+1].trim()){
                    str[i] = "";
                }
            }
            for(int j=0;j<str.length;j++){
                if(str[j] != ""){
                    selectionNotice=selectionNoticeService.get(str[j].trim());
                }
            }
            params.put("selectionNotice",selectionNotice);
        }

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        viewtype="";
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=selectionIssuedService.findByPagerAndLimit(false, "selectionissued", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=selectionIssuedService.findByPagerAndFinish("selectionissued", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=selectionIssuedService.findByPagerAndLimit(true, "selectionissued", pager, params);
        }

        List<SelectionIssued> selectionIssuedsList;
        if (pager.getTotalCount() > 0){

            selectionIssuedsList = (List<SelectionIssued>) pager.getList();
        }else{
            selectionIssuedsList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(SelectionIssued selectionIssued:selectionIssuedsList){
            rMap=new HashMap<>();
            rMap.put("id",selectionIssued.getId()!=null?selectionIssued.getId():"");
            rMap.put("post",selectionIssued.getSelectionNotice()!=null?selectionIssued.getSelectionNotice().getPost().getName():"");
            if(selectionIssued.getIssueStartDate()!=null&&selectionIssued.getIssueEndDate()!=null){
                rMap.put("issueDate",new SimpleDateFormat("yyyy-MM-dd").format(selectionIssued.getIssueStartDate())+" --- "+new SimpleDateFormat("yyyy-MM-dd").format(selectionIssued.getIssueEndDate()));
            }else{
                rMap.put("issueDate","");
            }
            rMap.put("processState",selectionIssued.getProcessState().key()==2?"聘书发放完成":"");

            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 自定义过滤器
     * @param _search
     * @param params
     * @param filters
     * @return
     */
    public Map getSearchFilterParams(String _search,Map<String,Object> params,String filters){
        //createAlias Key集合
        List<String> alias = new ArrayList<String>();
        if(org.apache.commons.lang3.StringUtils.isNotEmpty(_search)){
            boolean __search = Boolean.parseBoolean(_search);
            if(__search&& org.apache.commons.lang3.StringUtils.isNotEmpty(filters)){
                JSONObject filtersJson = JSONObject.fromObject(filters);
                if(org.apache.commons.lang3.StringUtils.equals(filtersJson.getString("groupOp"), "AND")){
                    //查询条件
                    JSONArray rulesJsons = filtersJson.getJSONArray("rules");
                    //遍历条件
                    for(int i=0;i<rulesJsons.size();i++){
                        JSONObject rule = rulesJsons.getJSONObject(i);
                        if(rule.has("field")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("field"))&&rule.has("data")&& org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                            String field = rule.getString("field");
                            if(field.contains("_")){
                                String[] fields = field.split("_");
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    params.put(field.replaceAll("_", "."), rule.getString("data"));
                                }
                            }else{
                                if(org.apache.commons.lang3.StringUtils.isNotEmpty(rule.getString("data"))){
                                    if(field.equals("issueStartDate")){
                                        params.put("issueStartDate", DataUtil.StringToDate(rule.getString("data")));
                                    }
                                    /*else {
                                        params.put(field, rule.getString("data"));
                                    }*/
                                }
                            }
                        }
                    }

                }
            }
        }

        return params;
    }
    public String read(){
        attchment=Lists.newArrayList();
        loginUser = usersService.getLoginInfo();
        selectionNotice=new SelectionNotice();
        if(StringUtils.isNotEmpty( keyId)) {
            Company company = usersService.getCompanyByUser();
            selectionIssued = selectionIssuedService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            //公告对象
            if(selectionIssued.getSelectionNotice()!=null){
                selectionNotice=selectionIssued.getSelectionNotice();
            }


            //附件对象
            if(selectionIssued.getAttchment()!=null){
                for(FileManage fileManage:selectionIssued.getAttchment()){
                    attchment.add(fileManage);
                }
            }
        }
        return "read";
    }

    public String input(){
        attchment=Lists.newArrayList();
        selectionNotice=new SelectionNotice();
        if (StringUtils.isNotEmpty(keyId)){
            selectionIssued = selectionIssuedService.get(keyId);
            Company company = usersService.getCompanyByUser();

            //附件对象
            if(selectionIssued.getAttchment()!=null){
                for(FileManage fileManage:selectionIssued.getAttchment()){
                    attchment.add(fileManage);
                }
            }
            //公告对象
            if(selectionIssued.getSelectionNotice()!=null){
                selectionNotice=selectionIssued.getSelectionNotice();
            }

        } else {

        }



        return "input";
    }

    private void setData(){
        attchment=Lists.newArrayList();
        selectionNotice=new SelectionNotice();
        if(StringUtils.isNotEmpty(keyId)){
            selectionIssued = selectionIssuedService.get(keyId);


        }else{
            selectionIssued = new SelectionIssued();
            selectionIssued.setCreater(usersService.getLoginInfo());

        }

        //公告对象
        if(StringUtils.isNotEmpty(parentId)){
            String[] str=parentId.split(",");
            for(int i=0;i<str.length-1;i++){
                if(str[i].trim()==str[i+1].trim()){
                    str[i] = "";
                }
            }
            for(int j=0;j<str.length;j++){
                if(str[j] != ""){
                    selectionNotice=selectionNoticeService.get(str[j].trim());
                }
            }
        }


        //附件对象
        if(StringUtils.isNotEmpty(issuedAttchmentId)){
            for(String s:issuedAttchmentId.split(",")){
                attchment.add(fileManageService.get(s.trim()));
            }
        }
        selectionIssued.setCreateDate(new Date());
        selectionIssued.setSelectionNotice(selectionNotice);
        selectionIssued.setAttchment(attchment);
        selectionIssued.setAttchmentText(attchmentText);
        selectionIssued.setIssueStartDate(issueStartDate);
        selectionIssued.setIssueEndDate(issueEndDate);
        selectionIssued.setCompany(usersService.getLoginInfo().getCompany());

        selectionIssuedService.save(selectionIssued);

    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                selectionIssuedService.update(selectionIssued);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                selectionIssuedService.save(selectionIssued, "selectionissued", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        var2.put("initDuty", curDutyId);
        ArrayList<String> list = new ArrayList<String>();


      /*  var2.put("approvers", list);    // 会签人Ids*/
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                selectionIssuedService.approve(selectionIssued, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
                SelectionIssued selectionIssued=selectionIssuedService.get(keyId);
                SelectionNotice selectionNotice=selectionIssued.getSelectionNotice();
                selectionNotice.setSelectionFinished("1");
                selectionNoticeService.save(selectionNotice);
            } else {
                String id=selectionIssuedService.commit(selectionIssued, FlowEnum.ProcessState.Finished,"selectionissued",var1,var2,curDutyId);
                /*String id=selectionIssuedService.commit(selectionIssued, "selectionissued", var1, var2, curDutyId);*/
                SelectionIssued entity=selectionIssuedService.get(id);
                /*entity.setProcessState(FlowEnum.ProcessState.Finished);*/
                SelectionNotice selectionNotice=entity.getSelectionNotice();
                selectionNotice.setSelectionFinished("1");
                selectionNoticeService.save(selectionNotice);
                /*selectionIssuedService.save(entity);*/
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve1(){
        selectionIssued = selectionIssuedService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        //  var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                selectionIssuedService.approve(selectionIssued, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }
    // 会签
    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        Map<String, Object> var2 = new HashMap<String, Object>();

        selectionIssued = selectionIssuedService.get(keyId);
        /*Task task=workflowService.getCurrentTask(keyId, usersService.getLoginInfo());
      

        int multComplete = (Integer)runtimeService.getVariable(task.getExecutionId(),"nrOfCompletedInstances");
        int nrOfInstances = (Integer)runtimeService.getVariable(task.getExecutionId(),"nrOfInstances");
        LogUtil.info("multComplete:"+multComplete);
        LogUtil.info("nrOfInstances:"+nrOfInstances);

        if((double)multComplete/nrOfInstances>=1){
            var2.put("numStatus", 2);
            LogUtil.info("do:numStatus2");
        } else {
            var2.put("numStatus", 1);
            LogUtil.info("do:numStatus1");
        }*/

        //  var2.put("curDutyId", curDutyId);
        try {

            selectionIssuedService.approve(selectionIssued, FlowEnum.ProcessState.Running, var2, curDutyId, comment);

            Task overtask = workflowService.getCurrentTask(keyId);
            if(overtask==null){/*没有task就到了归档，所以*/
                SelectionIssued selectionIssued=selectionIssuedService.get(keyId);
                selectionIssued.setProcessState(FlowEnum.ProcessState.Finished);
                selectionIssuedService.update(selectionIssued);


                /*selectionSpeech= new SelectionSpeech();
                selectionSpeech.setCreater(selectionIssued.getCreater());
                selectionSpeech.setCreateDate(new Date());
                selectionSpeech.setSpeechState("竞聘演讲");
                selectionSpeech.setSelectionIssued(selectionIssued);
                selectionSpeech.setResult("未审批");
                selectionSpeech.setSelectionNotice(selectionIssued.getSelectionNotice());
                selectionSpeech.setCompany(selectionIssued.getCreater().getCompany());
                selectionSpeechService.save(selectionSpeech);*/


            }else {
                if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 3);
                }
            }
    } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        selectionIssued = selectionIssuedService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            selectionIssuedService.approve(selectionIssued, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            selectionIssued = selectionIssuedService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("selectionissued");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            selectionIssuedService.reject(selectionIssued, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            selectionIssued = selectionIssuedService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("selectionissued");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            selectionIssuedService.deny(selectionIssued, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public SelectionIssued getSelectionIssued() {
        return selectionIssued;
    }

    public void setSelectionIssued(SelectionIssued selectionIssued) {
        this.selectionIssued = selectionIssued;
    }
    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getViewtype() {
        return viewtype;
    }
    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public String getIssuedAttchmentId() {
        return issuedAttchmentId;
    }

    public void setIssuedAttchmentId(String issuedAttchmentId) {
        this.issuedAttchmentId = issuedAttchmentId;
    }

    public Date getIssueStartDate() {
        return issueStartDate;
    }

    public void setIssueStartDate(Date issueStartDate) {
        this.issueStartDate = issueStartDate;
    }

    public Date getIssueEndDate() {
        return issueEndDate;
    }

    public void setIssueEndDate(Date issueEndDate) {
        this.issueEndDate = issueEndDate;
    }

    public List<FileManage> getAttchment() {
        return attchment;
    }

    public void setAttchment(List<FileManage> attchment) {
        this.attchment = attchment;
    }

    public String getAttchmentText() {
        return attchmentText;
    }

    public void setAttchmentText(String attchmentText) {
        this.attchmentText = attchmentText;
    }

    public SelectionNotice getSelectionNotice() {
        return selectionNotice;
    }

    public void setSelectionNotice(SelectionNotice selectionNotice) {
        this.selectionNotice = selectionNotice;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

}


